package com.it00zyq.admin.util;

import com.it00zyq.admin.result.HotArticleResult;
import com.it00zyq.common.entity.Article;
import com.it00zyq.common.mapper.ArticleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @Author zyq
 * @Date 2022/5/2 17:47
 * @Description TODO
 * @Version 1.0
 **/
@Component
@RequiredArgsConstructor
public class HotArticleUtil {

    private final ArticleMapper mapper;
    private final static int MAX_SIZE = 10;
    private Map<Integer, HotArticleResult> map = new HashMap<>(MAX_SIZE);

    public void insert(HotArticleResult e) {
        if (ObjectUtils.isEmpty(e)) {
            return ;
        }

        if (map.containsKey(e.getId()) || map.size() < MAX_SIZE) {
            map.put(e.getId(), e);
        } else {
            int min1 = Integer.MAX_VALUE;
            Integer minId1 = null;
            // 找到map中阅读量最小的元素
            for (Map.Entry<Integer, HotArticleResult> entry : map.entrySet()) {
                Integer value = entry.getValue().getReadCount();
                if (value < min1) {
                    min1 = value;
                    minId1 = entry.getValue().getId();
                }
            }

            // 若要添加的元素的阅读量大于最小值，需要移除最小，添加新元素
            if (min1 < e.getReadCount()) {
                map.remove(minId1);
                map.put(e.getId(), e);
            }
        }
    }


    /**
     * 获取阅读量排名前十的文章列表
     */
    public List<HotArticleResult> getHotList() {
        List<HotArticleResult> res = new ArrayList<>(map.size());
        for (Map.Entry<Integer, HotArticleResult> entry : map.entrySet()) {
            HotArticleResult value = entry.getValue();
            Article article = mapper.selectById(value.getId());
            if (!ObjectUtils.isEmpty(article)) {
                value.setTitle(article.getTitle());
            }
            res.add(entry.getValue());
        }
        Collections.sort(res);
        return res;
    }
}
